package com.hlj.ncp.finance.controller;

import com.hlj.ncp.common.core.domain.AjaxResult;
import com.hlj.ncp.finance.entity.Order;
import com.hlj.ncp.finance.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 订单信息Controller
 */
@Controller
@RequestMapping("/finance/order")
public class OrderController {
    @Autowired
    private IOrderService orderService;

    /**
     * 订单管理页面
     */
    @GetMapping("/index")
    public String index() {
        return "order/index";
    }

    /**
     * 查询订单信息列表
     */
    @PreAuthorize("hasPermission('finance:order:list')")
    @GetMapping("/list")
    @ResponseBody
    public AjaxResult list(Order order) {
        List<Order> list = orderService.selectOrderList(order);
        return AjaxResult.success(list);
    }

    /**
     * 获取订单总数
     */
    @GetMapping("/count")
    @ResponseBody
    public AjaxResult count() {
        long count = orderService.count();
        return AjaxResult.success(count);
    }

    /**
     * 获取订单图表数据
     */
    @GetMapping("/chart")
    @ResponseBody
    public AjaxResult getOrderChart() {
        // 创建模拟的订单图表数据
        Map<String, Object> chartData = new HashMap<>();

        // 最近6个月的标签
        List<String> monthLabels = new ArrayList<>();
        List<Integer> orderCounts = new ArrayList<>();
        List<BigDecimal> orderAmounts = new ArrayList<>();

        // 获取最近6个月的日期标签
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

        for (int i = 5; i >= 0; i--) {
            LocalDate monthDate = now.minusMonths(i);
            monthLabels.add(monthDate.format(formatter));

            // 生成随机订单数量和金额数据(模拟数据)
            Random random = new Random();
            int orderCount = 20 + random.nextInt(80); // 20-100的随机订单数
            BigDecimal amount = new BigDecimal(10000 + random.nextInt(90000))
                    .divide(new BigDecimal(100)); // 100-1000的随机金额

            orderCounts.add(orderCount);
            orderAmounts.add(amount);
        }

        chartData.put("months", monthLabels);
        chartData.put("counts", orderCounts);
        chartData.put("amounts", orderAmounts);

        // 订单类型分布
        Map<String, Integer> orderTypes = new HashMap<>();
        orderTypes.put("销售", 45);
        orderTypes.put("采购", 30);
        orderTypes.put("退货", 15);
        orderTypes.put("其他", 10);
        chartData.put("types", orderTypes);

        return AjaxResult.success(chartData);
    }

    /**
     * 获取最近的订单
     */
    @GetMapping("/recent")
    @ResponseBody
    public AjaxResult getRecentOrders(@RequestParam(required = false, defaultValue = "5") Integer limit) {
        // 创建模拟的最近订单数据
        List<Map<String, Object>> recentOrders = new ArrayList<>();

        // 模拟订单数据
        String[] orderTypes = {"销售订单", "采购订单", "退货订单"};
        String[] statusTypes = {"待付款", "已付款", "已发货", "已完成", "已取消"};
        String[] customers = {"北京农产品有限公司", "上海农产贸易中心", "广州果蔬配送有限公司",
                "深圳市农产品集团", "杭州农业科技有限公司"};

        Random random = new Random();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        for (int i = 0; i < limit; i++) {
            Map<String, Object> order = new HashMap<>();

            order.put("orderId", 10000 + random.nextInt(10000));
            order.put("orderCode", "ORD" + (20220000 + random.nextInt(10000)));
            order.put("orderType", orderTypes[random.nextInt(orderTypes.length)]);
            order.put("customerName", customers[random.nextInt(customers.length)]);
            order.put("amount", new BigDecimal(random.nextInt(1000000) / 100.0).setScale(2, BigDecimal.ROUND_HALF_UP));
            order.put("status", statusTypes[random.nextInt(statusTypes.length)]);

            // 创建最近30天内的随机日期
            LocalDateTime orderTime = LocalDateTime.now().minusDays(random.nextInt(30));
            order.put("createTime", orderTime.format(formatter));

            recentOrders.add(order);
        }

        return AjaxResult.success(recentOrders);
    }

    /**
     * 获取订单信息详细信息
     */
    @PreAuthorize("hasPermission('finance:order:query')")
    @GetMapping(value = "/{orderId}")
    @ResponseBody
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId) {
        return AjaxResult.success(orderService.selectOrderById(orderId));
    }

    /**
     * 新增订单信息
     */
    @PreAuthorize("hasPermission('finance:order:add')")
    @PostMapping
    @ResponseBody
    public AjaxResult add(@RequestBody Order order) {
        return orderService.insertOrder(order) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 新增订单信息（扩展接口）
     */
    @PreAuthorize("hasPermission('finance:order:add')")
    @RequestMapping(value = "/add", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public AjaxResult addOrder(Order order) {
        if (order == null) {
            // 返回一个空的成功响应
            return AjaxResult.success("请提交订单数据");
        }

        // 生成订单编号
        if (order.getOrderCode() == null || order.getOrderCode().isEmpty()) {
            // 生成格式：ORD + 年月日 + 6位随机数字
            String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String randomNum = String.format("%06d", new Random().nextInt(1000000));
            order.setOrderCode("ORD" + dateStr + randomNum);
        }

        // 设置订单类型（如果为空）
        if (order.getOrderType() == null || order.getOrderType().isEmpty()) {
            order.setOrderType("2"); // 默认为销售订单
        }

        // 设置订单日期（如果为空）
        if (order.getOrderDate() == null) {
            order.setOrderDate(LocalDateTime.now());
        }

        // 设置默认状态
        if (order.getPayStatus() == null) {
            order.setPayStatus("0"); // 未支付
        }
        if (order.getDeliveryStatus() == null) {
            order.setDeliveryStatus("0"); // 未交付
        }
        if (order.getStatus() == null) {
            order.setStatus("0"); // 待处理
        }

        // 设置默认金额（如果为空）
        if (order.getOrderAmount() == null) {
            order.setOrderAmount(new BigDecimal("0.00"));
        }
        if (order.getPayAmount() == null) {
            order.setPayAmount(new BigDecimal("0.00"));
        }

        return orderService.insertOrder(order) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 修改订单信息
     */
    @PreAuthorize("hasPermission('finance:order:edit')")
    @PutMapping
    @ResponseBody
    public AjaxResult edit(@RequestBody Order order) {
        return orderService.updateOrder(order) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 删除订单信息
     */
    @PreAuthorize("hasPermission('finance:order:remove')")
    @PostMapping("/{orderIds}")
    @ResponseBody
    public AjaxResult remove(@RequestParam(name = "orderIds")@PathVariable String[] orderIds) {
        if (orderIds == null || orderIds.length == 0){
            return AjaxResult.error("请选择要删除的订单");
        }
        for (String orderId : orderIds) {
            if (!orderService.deleteOrderById(Long.parseLong(orderId))) {
                return AjaxResult.error("删除订单失败");
            }
        }
        return AjaxResult.success();
      //  return orderService.deleteOrderByIds(orderIds) ? AjaxResult.success() : AjaxResult.error();
    }
} 